#include "dx8_buffer.h"
#include "dx8_graphics.h"
#include <dxerr8.h>

#include "util/timer.h"				// log
#include "util/log.h"				// log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"		    

#include <cassert>



DX8VertexBuffer::DX8VertexBuffer(unsigned int Count, unsigned int StepSize, unsigned int FVF) :
	GraphicsBuffer(Count, StepSize),
	m_FVF(FVF),
	m_pBuffer(0)
{
	unsigned long	Usage = D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY;
	D3DPOOL	Pool = D3DPOOL_DEFAULT;
	if (GetDXGraphics()->HasBug(Dx8Graphics::BUG_SOFTWARE_PROCESSING)) 
	{
		Usage = Usage | D3DUSAGE_SOFTWAREPROCESSING;
		Pool = D3DPOOL_SYSTEMMEM;
	}
	HRESULT hRes= GetDXGraphics()->GetDevice()->CreateVertexBuffer(m_TotalSize, Usage, FVF, D3DPOOL_DEFAULT, &m_pBuffer);
}

DX8VertexBuffer::~DX8VertexBuffer()
{
	UTIL_SAFE_RELEASE(m_pBuffer);
}
void	DX8VertexBuffer::Load(void* pSrc, int Count)
{
	if (!m_pBuffer) return;
	if (Count*m_StepSize > m_TotalSize) return;

	unsigned char*	pData = NULL;
	HRESULT hRes = m_pBuffer->Lock(0, Count*m_StepSize, &pData, D3DLOCK_DISCARD);
	if (SUCCEEDED(hRes))
	{
		memcpy(pData, pSrc, Count*m_StepSize);
		m_pBuffer->Unlock();
	}
}
/////////////////////////////////////////////


DX8IndexBuffer::DX8IndexBuffer(unsigned int Count) :
	GraphicsBuffer(Count, sizeof(unsigned short)),
	m_pBuffer(0)
{
	unsigned long	Usage = D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY;
	D3DPOOL	Pool = D3DPOOL_DEFAULT;
	if (GetDXGraphics()->HasBug(Dx8Graphics::BUG_SOFTWARE_PROCESSING)) 
	{
		Usage = Usage | D3DUSAGE_SOFTWAREPROCESSING;
		Pool = D3DPOOL_SYSTEMMEM;
	}
	HRESULT hRes= GetDXGraphics()->GetDevice()->CreateIndexBuffer(m_TotalSize, Usage, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_pBuffer);
}

DX8IndexBuffer::~DX8IndexBuffer()
{
	UTIL_SAFE_RELEASE(m_pBuffer);
}
void	DX8IndexBuffer::Load(void* pSrc, int Count)
{
	if (!m_pBuffer) return;
	if (Count*m_StepSize > m_TotalSize) return;

	unsigned char*	pData = NULL;
	HRESULT hRes = m_pBuffer->Lock(0, Count*m_StepSize, &pData, D3DLOCK_DISCARD);
	if (SUCCEEDED(hRes))
	{
		memcpy(pData, pSrc, Count*m_StepSize);
		m_pBuffer->Unlock();
	}
}

